<?php declare(strict_types=1);

namespace app\home\controller;

use app\common\service\ArticleService;
use app\common\service\CasesService;
use app\common\service\CommonService;
use app\common\service\TagService;
use app\home\Diluma;
use app\Request;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\View;
use app\common\model\Nav;

class Cases extends Diluma
{
    /**
     * 首页
     * @return string
     */
    public function index(Request $request)
    {
        $service = new CasesService();
        $keywords = $request->get('keywords', '');
        $categoryId = $request->get('category_id', 8, 'intval');
        $page = $request->get('page', 1);
//        // 案例
        $items = $service->getCasesList($categoryId, false,12, $page, $keywords);
//        // header
          $this->getHeader(1, new Nav(), 2);
//        View::assign('category', ['id'=>$categoryId, 'name'=>$categoryName]);
        View::assign('cases_list', $items);
        $caseNum = (new CasesService())->getCasesNum(8);
        View::assign('cur_location', (new CommonService())->getCurLocation(2));
        View::assign('case_num', $caseNum);
        return View::fetch();
    }

    /**
     * 详情
     * @param $id
     * @param int $categoryId
     * @return string
     * @throws DbException
     */
    public function detail($id, int $categoryId = 0)
    {
        $service = new CasesService();
        $item = $service->getCasesDetail($id);
        if (empty($item)) {
            return View::fetch('404.html');
        }
        if ($item->images_url) {
            $item->images_url = explode(';', rtrim($item->images_url, ';'));
        }
        // 上一篇
        $prevArticle = $service->getPrevCases($id, $categoryId);
        // 下一篇
        $nextArticle = $service->getNextCases($id, $categoryId);
        // 推荐案例
        $casesItems = $service->getCasesList(0, true,3);
        // header
        $this->getHeader(1, new \app\common\model\Cases(), $item->category_id, $id);
        View::assign('data', $item);
        View::assign('cur_location', (new CommonService())->getCurPos(new \app\common\model\Cases(), $item->category_id, $id));
        View::assign('rec_cases', $casesItems);
        View::assign('prev', $prevArticle);
        View::assign('next', $nextArticle);
        // 更新浏览量
        $service->views($id);
        return View::fetch();
    }

    /**
     * 猜你喜欢
     * @return string
     */
    public function like(Request $request)
    {
        $service = new CasesService();
        // 案例
        $items = $service->getCasesBy(['is_rec'=>1], 9);
        if (!empty($items)) {
            foreach ($items as &$cases) {
                $cases->linkurl = url('/home/cases/detail', ['category_id' => $cases->category_id, 'id' => $cases->id])->build();
            }
        }
        return json(['code'=>0, 'count'=>$items->total(), 'data'=>$items->items()]);
    }
}